<template>

  <el-container>
    <el-header>
      <h3 v-text="!dataForm.id ? '新增' : '修改'"></h3>
    </el-header>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="18">
          <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                   label-width="150px">
            <el-form-item label="商品名称" prop="spuName">
              <el-input v-model="dataForm.spuName" placeholder="商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="spuDescription">
              <el-input v-model="dataForm.spuDescription" placeholder="商品描述"></el-input>
            </el-form-item>
            <el-form-item label="所属分类" prop="catalogId">
              <!--              <el-input v-model="dataForm.catalogId" placeholder="所属分类id"></el-input>-->
              <category-tree-cascader @category-lowest-level-change="updateCatelogId($event)"
                                      :categoryId="catelogIdForCascader"></category-tree-cascader>
            </el-form-item>
            <el-form-item label="品牌id" prop="brandId">
              <!--              <el-input v-model="dataForm.brandId" placeholder="品牌id"></el-input>-->

              <el-select v-model.trim="dataForm.brandId"
                         filterable
                         allow-create
                         placeholder="请选择" @focus="brandTips">
                <el-option
                  v-if="availableBrandList.length>0"
                  v-for="item in availableBrandList"
                  :key="item.brandId"
                  :label="item.name"
                  :value="item.brandId">
                </el-option>
              </el-select>

            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <el-input-number :min="0.1" :step="0.1" v-model="dataForm.weight" placeholder=""></el-input-number>
              Kg
            </el-form-item>


            <el-form-item label="设置积分">
              <!--
                    <el-table-column
                      prop="growBounds"
                      header-align="center"
                      align="center"
                      label="成长积分">
                    </el-table-column>
                    <el-table-column
                      prop="buyBounds"
                      header-align="center"
                      align="center"
                      label="购物积分">
                    </el-table-column>
              -->
              金币：
              <el-input-number v-model="dataForm.buyBounds" controls-position="right" :min="0"></el-input-number>
              成长值：
              <el-input-number v-model="dataForm.growBounds" controls-position="right" :min="0"></el-input-number>
            </el-form-item>

            <el-form-item label="上架状态" prop="publishStatus">
              <!--              [0 - 下架，1 - 上架]-->
              <!--              <el-input v-model="dataForm.publishStatus" placeholder="上架状态[0 - 下架，1 - 上架]"></el-input>-->
              <el-tooltip :content="dataForm.publishStatus===1?'上架':'下架'" placement="top">
                <el-switch
                  v-model="dataForm.publishStatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="商品描述">

              <!--<el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="dataForm.spuInfoDescEntity.decript"
                show-word-limit>

              </el-input>-->
              <upload-single-file @update-file-list="updateSpuInfoDescEntityDecript($event)"></upload-single-file>
            </el-form-item>
            <el-form-item label="请选择商品图片">
              <upload-single-file @update-file-list="updateImages($event)"
                                  :fileListUrl="imagesForUploadList"></upload-single-file>
            </el-form-item>
            <el-form-item label="添加日期">
              <el-date-picker
                disabled
                v-model="dataForm.createTime"
                type="datetime"
                placeholder="系统自动更新">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="修改日期">
              <el-date-picker
                disabled
                v-model="dataForm.updateTime"
                type="datetime"
                placeholder="系统自动更新">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
          </span>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple"></div>
        </el-col>
      </el-row>
      <el-button @click="dataFormSubmit">测试提交</el-button>
    </el-main>
  </el-container>

</template>

<script>
import categoryTreeCascader from '../../common/categoryTreeCascader'
import CategoryBrandRelationApi from '../../../../api/product/CategoryBrandRelationApi'
import uploadSingleFile from '../../../../components/upload/uploadSingleFile'
import brandApi from '../../../../api/product/brandApi'
import uploadToAiliOss from '../../../../api/uploadToAiliOss'

export default {
  components: {
    categoryTreeCascader,
    uploadSingleFile
  },
  props: ['hub'],
  data () {
    return {
      visible: true,
      dataForm: {
        'brandId': null,        //品牌id
        'catalogId': null,      //所属分类
        'publishStatus': null,  //上架状态
        'spuDescription': null, //商品描述
        'spuName': null,  //商品名称
        'weight': null,   //商品重量
        'images': [
          {
            'defaultImg': null,
            'id': null,
            'imgName': null,
            'imgSort': null,
            'imgUrl': null,
            'spuId': null
          }
        ],
        'spuInfoDescEntity': {
          'decript': null,    //商品详细描述
          'spuId': null
        },
      },
      localHub: null,
      catelogIdForCascader: null,
      imagesForUploadList: [],
      dataRule: {
        spuName: [
          {required: true, message: '商品名称不能为空', trigger: 'blur'}
        ],
        spuDescription: [
          {required: true, message: '商品描述不能为空', trigger: 'blur'}
        ],
        catalogId: [
          {required: true, message: '所属分类id不能为空', trigger: 'blur'}
        ],
        brandId: [
          {required: true, message: '品牌id不能为空', trigger: 'blur'}
        ],
        weight: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        publishStatus: [
          {required: true, message: '上架状态[0 - 下架，1 - 上架]不能为空', trigger: 'blur'}
        ],
        createTime: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        updateTime: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ]
      },
      brandCurrentPage: 1,
      brandSize: 10,
      availableBrandList: [],
      hostAddress: null,
    }
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/pms/spuinfo/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {

              this.dataForm = data.supInfo
              /*              this.dataForm.spuName = data.spuInfo.spuName
                            this.dataForm.spuDescription = data.spuInfo.spuDescription
                            this.dataForm.catalogId = data.spuInfo.catalogId

                            this.catelogIdForCascader = data.spuInfo.catalogId

                            this.dataForm.brandId = data.spuInfo.brandId
                            this.dataForm.weight = data.spuInfo.weight
                            this.dataForm.publishStatus = data.spuInfo.publishStatus
                            this.dataForm.createTime = data.spuInfo.createTime
                            this.dataForm.updateTime = data.spuInfo.updateTime*/
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/pms/spuinfo/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData(this.dataForm),
            /*data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'spuName': this.dataForm.spuName,
              'spuDescription': this.dataForm.spuDescription,
              'catalogId': this.dataForm.catalogId,
              'brandId': this.dataForm.brandId,
              'weight': this.dataForm.weight,
              'publishStatus': this.dataForm.publishStatus,
              // 'createTime': this.dataForm.createTime,
              // 'updateTime': this.dataForm.updateTime
            })*/

          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    updateCatelogId (val) {
      console.log('所属三级分类id更新', val)
      this.dataForm.catalogId = val
      this.getAvailableBrandListByCategoryId()
    },
    brandTips () {
      if (this.dataForm.catalogId === null) {
        this.$message({
          message: '请先选择商品分类，才能选择商品品牌',
          type: 'warning'
        })
      }
    },
    async getAvailableBrandListByCategoryId (categoryId) {

      if (categoryId) {
        this.dataForm.catalogId = categoryId
      }

      let p = await CategoryBrandRelationApi.getBrandListPaginationByCategoryId(this.dataForm.catalogId, this.brandCurrentPage, this.brandSize)

      if (p.data.code != 0) {
        this.$message({
          message: `${this.dataForm.catalogId}没有与之对应的品牌可供选择`,
          type: 'warning'
        })
        console.log(p.data.data)
        return
      }

      console.log('可以选择的品牌是', p.data.page.list)

      this.availableBrandList = p.data.page.list
    },

    updateImages (imgList) {
      //TODO
      let imgObjArray = imgList.map(img => {
        if (img.raw) {
          return {
            key: img.raw.key,
            name: img.raw.name,
          }
        } else {
          console.log('我不是第一步上传的照片', img)
          return {
            key: img.url.substring(this.hostAddress.length),
            name: img.name,
          }
        }
      })

      imgObjArray = imgObjArray.filter(img => {
        return img != null
      })

      /**
       * 先清空数组
       * */
      this.dataForm.images.length = 0

      // 往数组中放入已经上传的图片key
      imgObjArray.forEach((imgObj, index) => {

        this.dataForm.images.push({
          'defaultImg': null,
          'id': null,
          'imgName': imgObj.name,
          'imgSort': index,
          'imgUrl': imgObj.key,
          'spuId': null,
        })
      })

      console.log('图片列表已经更新', this.dataForm.images)

    },
    updateSpuInfoDescEntityDecript (imgList) {

      let imgUrlArray = imgList.map(img => {

        return img.raw.key
        // name:img.raw.name, 就只用放图片就行了

      })

      // console.log('上传的商品描述大图是', imgUrlArray)

      this.dataForm.spuInfoDescEntity.decript = imgUrlArray.join(',')

    },

    async getHostAddress () {

      let p = await uploadToAiliOss.getHostAddress()

      this.hostAddress = p.data.host + '/'
    }
  },
  created () {
    this.getHostAddress()
  },
  watch: {
    'dataForm.brandId' (val) {
      //console.log( this.availableBrandList)

      console.log('dataForm.brandId更新了', val, '品牌id = ', this.dataForm.brandId)

      /**
       * 如果传入的是数字，说明是brandId，而不是用户新增的品牌
       * 传入数字还有另外一种可能，就是已经新增好了品牌，将新增的品牌赋值给  dataForm.brandId，从而触发监听器
       * */
      if (/^[0-9]+$/.test(val)) {
        return
      }

      /*      for (let i = 0; i < this.availableBrandList.length; i++) {

              if (this.availableBrandList[i].brandId == val) {
                console.log('availableBrandList中已经有该品牌了，不往pms_brand表中新增品牌')
                return false;
              }
            }*/

      if (this.dataForm.catalogId == null) {
        this.$message({
          message: '要先选中品牌分类才能添加该品牌',
          type: 'warning'
        })
        this.dataForm.brandId = null
        return
      }
      /**
       * 新增这一条记录
       * 新增 pms_brand 和 pms_category_brand_relation
       * 新增的时候 this.dataForm.brandId 就是新增的名字
       * */
      brandApi.saveBrandAndBrandCategoryRelation(this.dataForm.brandId, this.dataForm.catalogId).then(({data}) => {

        console.log(data.brandEntity)
        this.$message({
          message: `品牌：${this.dataForm.brandId}添加成功`,
          type: 'success'
        })
        this.dataForm.brandId = data.brandEntity.brandId
      })

    },
    /**
     * 一次性绑定事件
     * */
    localHub (val) {
      val.$on('update-image-list-of-step1', (images => {
        this.dataForm.images = images
        console.log('步骤一中的images已经更新', this.dataForm)
      }))

    },

    'dataForm.images' (val) {

      this.imagesForUploadList = val.map(img => {
        return img.imgUrl
      })
    }

  },

}
</script>
